package com.itpeng.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itpeng.dao.OrderSettingDao;
import com.itpeng.exception.HealthException;
import com.itpeng.pojo.OrderSetting;
import com.itpeng.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Aythor:彭彦钦
 * @Data: 2020/9/23  20:53
 */
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 批量设置预约人数
     * @param orderSettingList
     */
    @Override
    public void add(List<OrderSetting> orderSettingList) {
        //对集合进行遍历
        for (OrderSetting orderSetting : orderSettingList) {
            //先去根据日期查询是否有该日期的预约设置
            OrderSetting osInDB = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
            //当存在预约设置时，就进行修改
            if (osInDB != null) {
                //当已预约数量小于修改后的可预约数量时，才进行修改，否则报错
                if (osInDB.getReservations() <= orderSetting.getNumber()) {
                    //根据日期进行修改
                    orderSettingDao.updateByOrderDate(orderSetting);
                } else {
                    //否则则报错
                    throw new HealthException(orderSetting.getOrderDate() + " 中已预约数量不能大于可预约数量");
                }
            }else {
                //当该日期不存在预约设置时，则进行添加
                orderSettingDao.add(orderSetting);
            }
        }

    }

    /**
     * 根据年月查询当月预约设置
     * @param month
     * @return
     */
    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String month) {
        //拼接年月，得到每月最早的一日和最晚的一日
        String dateBegin = month + "-01";
        String dateEnd = month + "-31";

        //查询数据库
        List<Map<String, Integer>> data = orderSettingDao.getOrderSettingByMonth(dateBegin, dateEnd);
        return data;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //先去根据日期查询是否有该日期的预约设置
        OrderSetting osInDB = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
        //当存在预约设置时，就进行修改
        if (osInDB != null) {
            //当已预约数量小于修改后的可预约数量时，才进行修改，否则报错
            if (osInDB.getReservations() <= orderSetting.getNumber()) {
                //根据日期进行修改
                orderSettingDao.updateByOrderDate(orderSetting);
            } else {
                //否则则报错
                throw new HealthException(orderSetting.getOrderDate() + " 中已预约数量不能大于可预约数量");
            }
        }else {
            //当该日期不存在预约设置时，则进行添加
            orderSettingDao.add(orderSetting);
        }
    }
}
